#include<iostream>
#include<thread>
#include<fstream>
#include<mutex>
#include<string>
#include<time.h>


using namespace std;

enum Log_lever {
	INFO,
	WARNING,
	ERROR
};

string current()//活得当前时间
{
	time_t tp;
	struct tm* p;
	time(&tp);          
	p = localtime(&tp); 
	string str =to_string(1 + p->tm_mon) + ":" + to_string(p->tm_mday) + ":" + to_string(p->tm_hour) + ":" + to_string(p->tm_min) ;
	return str;
}

class Log {
public:
	static void setLever(Log_lever l) { lever = l; };
	static bool Init(string p, Log_lever);
	static void Uninit() { fout.close(); };
	static void write();
	static Log* getInstance();
private:
	Log()=default;
	~Log() {};
	Log(const Log& t) = delete;
	Log& operator=(const Log& t) = delete;

	static const unsigned max_file = 1048576;//1M的大小
	static Log_lever lever;
	static Log* instance;
	static ofstream fout;
	static string path;
    static mutex m;
};

Log_lever Log::lever=INFO ;
Log* Log::instance = nullptr;
ofstream Log::fout;
mutex Log::m;
string Log::path;

bool Log::Init(string p,Log_lever l)
{
    m.lock();
	path = p;
	string file = p + current();
	fout.open(file,ofstream::app);//追加文件
	if (!fout.is_open())
		return false;
	m.unlock();
	return true;
}
Log* Log::getInstance() {
	
	if (instance == nullptr) {
        m.lock();
        if (instance == nullptr)
		instance = new Log;
        m.unlock();
	}
	return instance;
}
void Log::write()
{  
	while (fout.tellp() > max_file) {
		fout.close();//如果日志文件太大
		string filename = path+ current();
        m.lock();
		fout.open(filename);
        m.unlock();
		if (!fout.is_open())
			return ;
	}
	string me;
	switch (lever) {
		case(INFO): me = "INFO:"; break;
		case(WARNING):me = "WARNIN:"; break;
		case(ERROR):me = "ERROR:"; break;
		default:return;
	};
	me += current()+"hello world\n";
    m.lock();
	fout << me << endl;
    m.unlock();
}
int main() {
	string path="/home/lixiaoyao/linux/";
	if(Log::Init(path,INFO)==false) cout<<"error\n";
	Log::getInstance()->write();
	Log::Uninit();
	return 0;
}